package com.tanguy.user.utlis

import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * Created by dab on 2017/11/27 0027 16:39
 */
class RxBus private constructor(){
      val maps by lazy { HashMap<String, Subject<*>>() }

    companion object {
        val instance = RxBus()
    }

    /**
     * 注意:1.如果发生异常,就会自动取消订阅,可以使用retryWhen操作符进行重新订阅
     * 2.在页面销毁的时候,需要将Disposable设置为dispose(或者调用unregister方法,将这个反注册),否则会导致这个页面就泄漏
     *
     * @param tag
     * @param clazz
     * @param <T>
     * @return
    </T> */
    inline fun <reified T> register(tag: String): Observable<T> {
        val subject: Subject<T>
        if (maps.containsKey(tag)) {
            val subject1 = maps[tag]
            subject = if (subject1 is Subject<*>) {
                maps[tag] as Subject<T>
            } else {
                PublishSubject.create<T>()
            }
        } else {
            subject = PublishSubject.create<T>()
            maps.put(tag, subject)
        }
        return subject.ofType(T::class.java)
                // 这里加了异常重新订阅
                .retryWhen{it.flatMap {Observable.timer(50,
                TimeUnit.MILLISECONDS)}}
    }

    fun post(tag: String, o: Any) {
        if (maps.containsKey(tag)) {
            val subject1 = maps[tag] as Subject<Any>
            subject1.onNext(o)
        }
    }

    /**
     * 反注册
     *
     * @param tag
     */
    fun unregister(tag: String) {
        if (maps.containsKey(tag)) {
            maps.remove(tag)
        }

    }
}
